package com.atlin.project.service.impl;

import com.atlin.project.common.ErrorCode;
import com.atlin.project.contant.CommonConstant;
import com.atlin.project.exception.BusinessException;
import com.atlin.project.exception.ThrowUtils;
import com.atlin.project.mapper.BiTeamMapper;
import com.atlin.project.model.domain.BiTeam;
import com.atlin.project.model.domain.BiUserTeam;
import com.atlin.project.model.domain.chart.Chart;
import com.atlin.project.model.dto.biTeam.BiTeamQueryRequest;
import com.atlin.project.model.vo.BiTeamVO;
import com.atlin.project.service.BiTeamService;
import com.atlin.project.service.BiUserTeamService;
import com.atlin.project.service.ChartService;
import com.atlin.project.utils.sql.SqlUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author atlin
 * @description biTeam
 * @createDate date
 */
@Service
public class BiTeamServiceImpl extends ServiceImpl<BiTeamMapper, BiTeam>
        implements BiTeamService {

    @Resource
    private ChartService chartService;

    @Resource
    private BiUserTeamService biUserTeamService;

    @Override
    public void valid(BiTeam biTeam, boolean add) {
        Long chartId = biTeam.getChartId();
        Long createUserId = biTeam.getCreateUserId();
        Chart chart = chartService.getById(chartId);
        if (chart == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        if (!chart.getUserId().equals(createUserId)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
    }

    @Override
    public BiTeamVO getBiTeamVO(BiTeam biTeam, HttpServletRequest request) {
        return BiTeamVO.objToVo(biTeam);
    }

    /**
     * 获取查询包装类（用户根据哪些字段查询，根据前端传来的请求对象，得到 mybatis 框架支持的查询 QueryWrapper 类）
     *
     * @param biTeamQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<BiTeam> getQueryWrapper(BiTeamQueryRequest biTeamQueryRequest) {
        QueryWrapper<BiTeam> queryWrapper = new QueryWrapper<>();
        if (biTeamQueryRequest == null) {
            return queryWrapper;
        }
        Long id = biTeamQueryRequest.getId();
        String sortField = biTeamQueryRequest.getSortField();
        String sortOrder = biTeamQueryRequest.getSortOrder();
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq("isDelete", false);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC), sortField);
        return queryWrapper;
    }

    @Override
    public Page<BiTeamVO> getBiTeamVOPage(Page<BiTeam> biTeamPage, HttpServletRequest request) {
        List<BiTeam> biTeamList = biTeamPage.getRecords();
        Page<BiTeamVO> biTeamVOPage = new Page<>(biTeamPage.getCurrent(), biTeamPage.getSize(), biTeamPage.getTotal());
        if (CollectionUtils.isEmpty(biTeamList)) {
            return biTeamVOPage;
        }

        // 填充信息
        List<BiTeamVO> biTeamVOList = biTeamList.stream().map(BiTeamVO::objToVo).collect(Collectors.toList());
        biTeamVOPage.setRecords(biTeamVOList);
        return biTeamVOPage;
    }

    @Override
    @Transactional
    public boolean disbandTeam(long teamId) {
        boolean result = biUserTeamService.deleteTeamUser(teamId);
        ThrowUtils.throwIf(!result, ErrorCode.SYSTEM_ERROR);

        LambdaQueryWrapper<BiUserTeam> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BiUserTeam::getTeamId, teamId);
        return removeById(teamId);
    }

    @Override
    @Transactional
    public boolean leaveTeam(Long userId, Long teamId) {
        BiTeam team = getById(teamId);
        if (team == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR, "团队不存在");
        }
        // 离开自己创建的团队，团队直接解散
        if (team.getCreateUserId().equals(userId)) {
            return this.disbandTeam(teamId);
        } else {
            return biUserTeamService.leaveUserTeam(userId, teamId);
        }
    }

    @Override
    public BiTeam getTeamByChartId(long chartId) {
        return getOne(new LambdaQueryWrapper<BiTeam>().eq(BiTeam::getChartId, chartId));
    }

    @Override
    public boolean checkUserBelongTeam(long userId, long chartId) {
        BiTeam team = getTeamByChartId(chartId);
        if (team == null) {
            return false;
        }
        BiUserTeam userTeam = biUserTeamService.getUserTeam(userId, team.getId());
        return userTeam != null;
    }
}




